<script lang="ts" setup>
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import { computed, h, reactive, ref, watch } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

// 导入Handsontable组件和样式
import { HotTable } from '@handsontable/vue3';
import { useDebounceFn } from '@vueuse/core';
import {
  Button,
  Col,
  Divider,
  InputNumber,
  message,
  Row,
  Select,
  Space,
  Spin,
  Switch,
  Tag,
} from 'ant-design-vue';
import Handsontable from 'handsontable';

import adapterFileLists from '#/adapter/component/FileManage/updataFile.vue';
import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getUserBaseApi } from '#/api';
import {
  allIndex,
  colorAll,
  colorSeriesTree,
  DictAddInit,
  ErpBrandList,
  getAttachFiled,
  getFactoryIndex,
  getGoodsStyleCategory,
  getSizeGroupList,
  getTreeAll,
  remoteSelect,
  ScmGoodsInfo,
} from '#/api/goods';
import { GoodsPurchseDetailedit } from '#/api/goodsPurchaseDetail';
import { toCascaderOptions } from '#/utils';
import submitApproval from '#/views/backend/modules/submitApproval.vue';

import FileList from './fileList.vue';
import ImageUploader from './imageUploader.vue';

import 'handsontable/dist/handsontable.full.css';

// 用于存储选中的单元格信息
const highlight = reactive({ row: -1, col: -1 });

// 全局定义和注册Handsontable渲染器
const negativeValueRenderer = (
  instance,
  td,
  row,
  col,
  prop,
  value,
  cellProperties,
) => {
  td.innerHTML = value == 0 || value == '' || value == null ? '' : value;

};
const negativeValueRenderer2 = (
  instance,
  td,
  row,
  col,
  prop,
  value,
  cellProperties,
) => {
  if (row == highlight.row && col == highlight.col) {
    td.className = 'custom-cell';
  }
  td.innerHTML = value == 0 || value == '' || value == null ? '' : value;
};

const isEdit: any = ref<boolean>(false);
const currentView = ref<string>('edit'); // 新增变量存储当前视图类型
const hasPurchaseDetail = ref<boolean>(false); // 用于控制采购信息的显示
const keyword1 = ref('');
const keyword2 = ref('');
const keyword3 = ref('');
const keyword4 = ref('');
const keyword5 = ref('');
const attrKeys = ref([]);
const fetching = ref(false);
const ingrImages = ref<any>(null); // 检测文件
const goodsImages = ref<any>(null); // 检测文件
const p__plan_total_num = ref<any>(null); // 检测文件
const is_price_checking = ref(false);
const upCongfig: any = ref(); // 货品图片数组

function onSubmit(values: Record<string, any>) {
  message.success({
    content: `form values: ${JSON.stringify(values)}`,
  });
}

// 字典下来数据
const selectFieldsKeys = [
  'buyerUsers',
  'merchUsers',
  'unevenColor',
  'thickness',
  'pattern',
  'ageName',
  'factionName',
  'warmColor',
  'colorSystem',
  'categoryLifecycle',
  'singleLifecycle',
  'displayFunds',
  'securityCategory',
  'execStandard',
  'pattern',
  'priceRange',
  'goodsRules',
  'tagVersion',
  'secondStyle',
  'designUser',
  'planningStyle',
  'goodsSex',
];

/**
 * 获取简码远程选项
 */
async function fetchRemoteOptions({ keyword = '' }: Record<string, any>) {
  console.log(keyword)
  let quick_search = '';
  let initValue = '';
  const initKey = 'template_id';
  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '');
    if (initValue) {
      initValue = keyword.replace('initValue:', '').split(',');
    }
  } else {
    quick_search = keyword;
  }
  const { list } = await remoteSelect({
    quick_search: quick_search,
    page: 1,
    limit: 999,
    initKey: initKey,
    initValue: initValue,
    select: true,
  });
  return list.map((item: any) => ({
    label: item.template_name,
    value: item.template_id,
  }));
}
/**
 * 获取颜色远程选项
 */
async function fetchColorOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await colorAll({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'color.id',
    initValue: undefined,
    select: true,
  });
  return list.map((item: any) => ({
    label: item.name,
    value: item.id,
    disabled: item.is_enabled,
  }));
}
/**
 * 获取品牌远程选项
 */
async function fetchBandOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await ErpBrandList({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'erp_brand_info.id',
    initValue: undefined,
    select: true,
  });
  return list.map((item: any) => ({
    label: item.title_chinese,
    value: item.id,
  }));
}

async function fetchGoodsStyleCategory({ keyword = '' }: Record<string, any>) {
  const { list } = await getGoodsStyleCategory({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  });
  return list.map((item: any) => ({
    label: item.style_category_name,
    value: item.id,
  }));
}

async function fetchgetFactoryIndex({ keyword = '' }: Record<string, any>) {
  const { list } = await getFactoryIndex({
    quick_search: keyword,
    page: 1,
    limit: 9999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  });
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }));
}

const selectBaseList = ref<Record<string, any>>({});
const selectSizeGroupList: any = ref(); // 字典
const idsArr: any = ref([]);
const categoryOptions = ref([]); // 货品分类树
const timeCategoryOptions = ref([]); // 货品波段树
const colorSeries: any = ref([]); // 色系树

// 获取字典
function getBaseList(arr: any) {
  const param = {
    keys: selectFieldsKeys,
    cate_arr: arr,
  };
  DictAddInit(param).then(({ select_list }) => {
    // 需要转成数组的字段
    const keys = selectFieldsKeys;
    // 统一处理
    selectBaseList.value = {
      ...select_list,
      ...Object.fromEntries(
        keys.map((k) => [
          k,
          Object.entries(select_list?.[k] || {}).map(([value, label]) => ({
            label,
            value,
          })),
        ]),
      ),
    };
  });
}

const buyerOptions = computed(() => selectBaseList.value.buyerUsers || []);
const merchUsersOptions = computed(() => selectBaseList.value.merchUsers || []);
const designUserOptions = computed(() => selectBaseList.value.designUser || []);
const planningStyleOptions = computed(
  () => selectBaseList.value.planningStyle || [],
);
const goodsRulesOptions = computed(() => selectBaseList.value.goodsRules || []);
const tagVersionOptions = computed(() => selectBaseList.value.tagVersion || []);
const selectSizeGroupOptions = computed(() => selectSizeGroupList.value || []);
const secondStyleOptions = computed(
  () => selectBaseList.value.secondStyle || [],
);
const ageNameOptions = computed(() => selectBaseList.value.ageName || []);
const patternOptions = computed(() => selectBaseList.value.pattern || []);
const thicknessOptions = computed(() => selectBaseList.value.thickness || []);
const priceRangeOptions = computed(() => selectBaseList.value.priceRange || []);
const factionNameOptions = computed(
  () => selectBaseList.value.factionName || [],
);
const execStandardOptions = computed(
  () => selectBaseList.value.execStandard || [],
);
const securityCategoryOptions = computed(
  () => selectBaseList.value.securityCategory || [],
);
const singleLifecycleOptions = computed(
  () => selectBaseList.value.singleLifecycle || [],
);
const categoryLifecycleOptions = computed(
  () => selectBaseList.value.categoryLifecycle || [],
);
const displayFundsOptions = computed(
  () => selectBaseList.value.displayFunds || [],
);
const goodsSexOptions = computed(() => selectBaseList.value.goodsSex || []);
// 获取尺码
function getSizeGroup(category: any) {
  const param = {
    category_id: category,
  };
  getSizeGroupList(param).then((response) => {
    selectSizeGroupList.value = response.list.map((item: any) => ({
      label: item.name,
      value: item.id,
    }));
  });
}

const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存';
});

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  confirmText: Text,
  fullscreen: true,
  appendToMain: true,
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    save();
  },
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) return;

    // 注册渲染器
    Handsontable.renderers.registerRenderer(
      'negativeValueRenderer',
      negativeValueRenderer,
    );
    Handsontable.renderers.registerRenderer(
      'negativeValueRenderer2',
      negativeValueRenderer2,
    );

    // 1. 先并行拉取级联数据
    const [cateRes, timeRes, colors] = await Promise.all([
      allIndex(),
      getTreeAll(),
      colorSeriesTree(),
    ]);
    categoryOptions.value = cateRes.list;
    timeCategoryOptions.value = timeRes;
    colorSeries.value = toCascaderOptions(colors.list);
    handleSupplySearch('');
    // 2. 处理编辑回显
    const { ids, view, purchase_detail_id } =
      modalApi.getData<Record<string, any>>();
    currentView.value = view || 'edit'; // 保存当前视图类型
    hasPurchaseDetail.value = !!purchase_detail_id; // 设置是否有采购详情（转换为布尔值）
    if (Array.isArray(ids)) {
      // 如果是多个编辑
      idsArr.value = ids;
      initData(ids[0]);
    } else {
      if (ids) {
        initData(ids, purchase_detail_id);
      }
    }
    isEdit.value = view === 'edit';
  },
});

async function save() {
  const { valid } = await baseFormApi.validate();
  if (!valid) return;
  // 提取所有URL并清理格式
  const urls = goodsImages.value
    ?.map((item: any) => {
      if (item.url) {
        // 清理URL中的反引号和空格
        return item.url.replaceAll(/[`\s]/g, '');
      }
      return '';
    })
    .filter(Boolean); // 过滤掉空字符串
  if (urls && urls.length > 0) {
    await baseFormApi.setValues({
      goods_images: urls,
    });
  }

  await baseFormApi.setValues({
    stock_data: showStock.data,
  });
  const tableData = gridApi.grid.getData();
  const values = await baseFormApi.getValues();
  values.supply_list = tableData;

  values.attr_json = attrKeys.value.reduce((acc, key) => {
    if (values[key] !== undefined) {
      acc[key] = values[key];
    }
    return acc;
  }, {});

  values.p__jg_price = values.p__jg_price?.toString();
  values.p__plan_total_num = values.p__plan_total_num?.toString();

  // 将Proxy对象和复杂对象转换为普通JavaScript对象
  modalApi.lock(true);
  if (isEdit.value) {
    GoodsPurchseDetailedit(values).then((res: any) => {
        if (res.data.code === 201) {
          submitApprovalModalApi.setData({ data: res.data.data }).open();
          modalApi.unlock();
          return;
        }else if(res.data.code === 0){
          modalApi.unlock();
          message.success({
            content:res.data.msg,
          });
        }else if(res.data.code === 1){
          message.success({
            content: `保存成功`,
          })
          modalApi.unlock();
          modalApi.close();
        }

      })
      .catch(() => {
        modalApi.unlock();
      });
  }
}

function convertToNormalObject(data) {
  const result = {};
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      const item = data[key];
      // 确保 attr_key 和 value 都存在
      if (item && item.attr_key !== undefined && item.value !== undefined) {
        result[item.attr_key] = item.value;
      }
    }
  }
  return result;
}
const p_posted = ref(0);
async function initData(id: any, purchase_detail_id?: string) {
  modalApi.lock();
  const { row } = await ScmGoodsInfo({
    goods_id: id,
    goods_purchase_detail_id: purchase_detail_id,
  });
  if (row) {
    modalApi.unlock();
  }
  row.goods_purchase_detail_id = purchase_detail_id;
  p_posted.value = row.p_posted;

  const attrJsonObject = JSON.parse(row.attr_json);
  const attr_json = convertToNormalObject(attrJsonObject);
  const dt = { ...row, ...attr_json };
  is_price_checking.value = row.is_price_checking;
  await baseFormApi.setValues(dt, false);
  keyword1.value = 'initValue:'+row.template_id;
  p__plan_total_num.value = row.p__plan_total_num;
  ingrImages.value = row.ingr_images || [];

  existingImages.value = row.ingr_images || [];
  goodsImages.value = row.goods_images || [];
  gridApi.setGridOptions({ data: row.supply_list || [] });
  getBaseList(row.category);
  handleAdd(row.category_id, purchase_detail_id);
  // 处理stock_data字段，设置到showStock.data中
  // if (row.stock_data && Array.isArray(row.stock_data) && row.stock_data.length > 0) {

  showStock.data = row.stock_data;
  // 调用initCurrentNum函数计算合计和平均值
  initCurrentNum();
  hotTableComponent.value.hotInstance.loadData(showStock.data);

  // 获取字典
  getBaseList(row.category_id);
  // 获取尺码组
  getSizeGroup(row.category_id);

  const { siteConfig } = await getUserBaseApi();
  upCongfig.value = siteConfig;
}
function handleAdd(category?: [], id?: any) {
  const parmast = {
    attrJson: [],
    category,
    id,
  };
  let from = [];
  getAttachFiled(parmast).then((res: any) => {
    attrKeys.value = res.data_list.map((item: any) => item.attr_key);
    from = res.data_list.map((item: any) => {
      const { attr_key, attr_name, data_type, dict_item_list } = item;
      if (dict_item_list) {
        // 如果存在 dict_item_list，则生成 Select 组件
        return {
          component: 'Select',
          componentProps: {
            allowClear: true,
            filterOption: (input, option) => {
              return (option?.label || '')
                .toLowerCase()
                .includes(input.toLowerCase());
            },
            options: Object.entries(dict_item_list).map(([value, label]) => ({
              label,
              value,
            })),
            showSearch: true,
          },
          fieldName: attr_key,
          label: attr_name,
        };
      } else {
        // 根据 data_type 生成对应的组件
        if (data_type.includes('input-number')) {
          return {
            component: 'InputNumber',
            componentProps: {
              min: 0,
              precision: item.attr?.precision || 2,
              step: item.attr?.step || 1,
              stringMode: false,
            },
            fieldName: attr_key,
            label: attr_name,
          };
        } else if (data_type.includes('textarea')) {
          return {
            component: 'Textarea',
            componentProps: {
              allowClear: true,
              class: 'w-full',
            },
            fieldName: attr_key,
            label: attr_name,
          };
        } else {
          return {
            component: 'Input',
            componentProps: {
              allowClear: true,
              class: 'w-full',
            },
            fieldName: attr_key,
            label: attr_name,
          };
        }
      }
    });

    baseFormApi.setState((prev) => {
      return {
        schema: [...(prev?.schema ?? []), ...from],
      };
    });
  });
}

const [BaseForm, baseFormApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  commonConfig: {
    // 在label后显示一个冒号
    colon: true,
    // 所有表单项
    componentProps: {
      class: 'w-4/5',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: '',
      fieldName: '_divider',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'Input',
      disabled: isEdit,
      componentProps: {
        placeholder: '空，自动生成',
        allowClear: true,
      },
      fieldName: 'goods_no',
      label: '货号',
      help: '空，自动生成',
    },
    {
      component: 'ApiSelect',
      disabled: isEdit,
      // 对应组件的参数
      componentProps: () => {
        return {
          api: fetchRemoteOptions,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword1.value = value;
          }, 300),

          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword1.value || undefined,
          },
          showSearch: true,
          allowClear: true,
          immediate: false,
          alwaysLoad: true,
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword1.value = '';
          },
        };
      },
      // 字段名
      fieldName: 'template_id',
      // 界面显示的label
      label: '简码',
      rules: 'required',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        };
      },
    },
    {
      component: 'ApiSelect',
      disabled: isEdit,
      componentProps: () => {
        return {
          api: fetchColorOptions,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword2.value = value;
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword2.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        };
      },
      fieldName: 'color_id',
      label: '颜色',
      rules: 'required',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        };
      },
    },
    {
      component: 'Select',
      fieldName: 'buyer',
      label: '买手',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: buyerOptions,
        showSearch: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'merchandiser',
      label: '跟单人',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: merchUsersOptions,
        showSearch: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'goods_name',
      label: '品名',
      help: '输入:以输入为准；空:根据分类自动生成',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'ApiSelect',

      componentProps: () => {
        return {
          disabled: p_posted.value > 0,
          api: fetchBandOptions,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword3.value = value;
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword3.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        };
      },
      fieldName: 'erp_brand_id',
      label: '品牌',
      rules: 'required',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        };
      },
    },
    {
      component: 'Select',
      fieldName: 'goods_nature',
      label: '货品属性',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        mode: 'multiple',
        options: [
          {
            label: '成品',
            value: '1',
          },
          {
            label: '赠品',
            value: '2',
          },
          {
            label: '礼品',
            value: '3',
          },
        ],
        showSearch: true,
      },
    },


    {
      component: 'Select',
      fieldName: 'design_user',
      label: '设计师',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: designUserOptions,
        showSearch: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'planning_style',

      label: '企划风格',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: planningStyleOptions,
        showSearch: true,
      },
    },
    {
      component: '',
      label: '货品图片',
      formItemClass: 'col-span-2 col-start-1',
      fieldName: 'goods_images',
    },
    {
      component: '',
      fieldName: 'ingr_images',
      formItemClass: 'col-span-2',
      label: '成分检测',
    },

    {
      component: '',
      fieldName: 'purchInfo',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchgetFactoryIndex,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword4.value = value;
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword4.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        };
      },
      fieldName: 'p_supply_id',
      label: '供货商',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        };
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'p__plan_total_num',

      label: '采购数量',
      componentProps: () => ({
        disabled: p_posted.value > 0,
        min: 0,
        precision: 0,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'p__price',
      label: '本次采购价',
      help: '大货采购单的采购价',
      valueToString: true,
      componentProps: () => ({
        disabled: p_posted.value > 0,
        min: 0,
        precision: 4,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'p__jg_price',
      help: '大货采购单的加工费',
      label: '本次加工费',
      componentProps: () => ({
        disabled: p_posted.value > 0,
        min: 0,
        precision: 4,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'DatePicker',
      defaultValue: undefined,
      fieldName: 'p__expected_completion_date',
      label: '货期',
      componentProps: () => ({
        disabled: p_posted.value > 0,
        valueFormat: 'YYYY-MM-DD',
      }),
    },
    {
      component: 'Textarea',
      fieldName: 'p__paving_area',
      label: '本次铺货区域',
    },
    {
      component: 'Textarea',
      fieldName: 'p__remark',
      label: '供应链备注',
    },

    {
      component: '',
      fieldName: 'warehouse',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: '',
      fieldName: 'compartment',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },

    {
      component: '',
      fieldName: '_divider1',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'Select',
      fieldName: 'goods_rules',
      label: '货号规则',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        options: goodsRulesOptions,
      },
    },
    {
      component: 'Select',
      fieldName: 'is_rfid',
      label: '是否RFID货品',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
        showSearch: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'has_ail',
      rules: 'required',
      label: 'RFID干扰材质',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
        showSearch: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'tag_version',
      label: '吊牌版本号',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        options: tagVersionOptions,
      },
    },
    {
      component: 'Select',
      fieldName: 'rfid_check',
      label: '启用RFID盘点',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
        showSearch: true,
      },
    },
    {
      component: '',
      fieldName: '_divider2',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'Cascader',
      fieldName: 'category_id',
      label: '分类',
      rules: 'required',
      componentProps: {
        options: categoryOptions,
        placeholder: '请选择',
        showSearch: true,
        allowClear: true,
        onChange: (value: any) => {
          getBaseList(value);
          getSizeGroup(value);
        },
      },
    },
    {
      component: 'Cascader',
      fieldName: 'bd_id',
      rules: 'required',
      label: '波段',
      componentProps: {
        options: timeCategoryOptions,
        placeholder: '请选择',
        showSearch: true,
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'size_group_id',
      label: '尺码组',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: selectSizeGroupOptions,
        showSearch: true,
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchGoodsStyleCategory,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword5.value = value;
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword5.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        };
      },
      fieldName: 'one_style_id',
      label: '一级风格',
      rules: 'required',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        };
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '引流款',
            value: 1,
          },
          {
            label: '基本款',
            value: 2,
          },
        ],
        showSearch: true,
      },
      fieldName: 'three_style_id',
      rules: 'required',
      label: '风格',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: secondStyleOptions,
        showSearch: true,
      },
      fieldName: 'second_style',
      rules: 'required',
      label: '二级风格',
    },
    {
      component: '',
      fieldName: '_divider3',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'InputNumber',
      fieldName: 'sale_price',
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'inventory_claim_price',
      label: '盘点赔付价',
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'return_price',
      label: '退货价',
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'tag_price',
      disabled: true,
      label: '吊牌价',
      componentProps: {
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'weight_price',
      label: '加权单价',
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'purchase_price',
      label: '采购价',
      disabled: true,
      help: '自动获取默认的供货商的采购价',
      componentProps: {
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'direct_price',
      label: '直营配货价',
      disabled: true,
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'estimated_cost',
      disabled: true,
      label: '成本价',
      componentProps: {
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'current_settle_price',
      disabled: true,
      label: '当前结算价',
      componentProps: {
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'distribution_price',
      label: '分销价',
      help: '加盟配货价',
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'distribution_price_history',
      label: '历史分销价',
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: 'InputNumber',
      fieldName: 'wholesale_price',
      label: '批发价',
      componentProps: () => ({
        disabled: is_price_checking.value,
        min: 0,
        precision: 2,
        step: 1,
        stringMode: false,
      }),
    },
    {
      component: '',
      fieldName: '_divider4',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: '',
      fieldName: 'but',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: '',
      fieldName: '_divider5',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },
    {
      component: 'Cascader',
      fieldName: 'color_series_id',
      label: '色系',
      help: '色系、色感、深浅色',
      componentProps: {
        options: colorSeries,
        placeholder: '请选择',
        showSearch: true,
        allowClear: true,
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: ageNameOptions,
        showSearch: true,
      },
      fieldName: 'age_name',
      rules: 'required',
      label: '适龄段',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: patternOptions,
        showSearch: true,
      },
      fieldName: 'template_type',
      label: '版型',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: thicknessOptions,
        showSearch: true,
      },
      fieldName: 'thickness',
      label: '厚薄度',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: factionNameOptions,
        showSearch: true,
      },
      fieldName: 'faction_name',
      label: '时尚度',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: displayFundsOptions,
        showSearch: true,
      },
      fieldName: 'display_funds',
      label: '陈列款',
    },
    {
      component: 'InputNumber',
      fieldName: 'gram_weight',
      label: '克重',
      rules: 'required',
      help: '称重标准:\n' + '外套180\n' + '裤子32\n' + '内搭52\n' + 'XL码',
      componentProps: {
        min: 0,
        precision: 1,
        step: 1,
        stringMode: false,
      },
    },

    {
      component: 'Select',
      rules: 'required',
      componentProps: {
        filterOption: (input, option) => {
          return (option?.label || '')
            .toLowerCase()
            .includes(input.toLowerCase());
        },
        options: goodsSexOptions,
      },
      fieldName: 'sex',
      label: '性别',
    },

    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: priceRangeOptions,
        showSearch: true,
      },
      fieldName: 'price_range',
      label: '价格带',
    },

    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: execStandardOptions,
        showSearch: true,
      },
      fieldName: 'exec_standard',
      label: '执行标准',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: securityCategoryOptions,
        showSearch: true,
      },
      fieldName: 'security_category',
      label: '安全类别',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: singleLifecycleOptions,
        showSearch: true,
      },
      fieldName: 'single_lifecycle',
      label: '单款销售生命周期',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: categoryLifecycleOptions,
        showSearch: true,
      },
      fieldName: 'category_lifecycle',
      label: '品类生命周期(天)',
    },

    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
      },
      fieldName: 'grade',
      label: '等级',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        class: 'w-full',
      },
      fieldName: 'similar',
      label: '类似款',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        class: 'w-full',
      },
      fieldName: 'shipping_remark',
      label: '铺货备注',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        class: 'w-full',
      },
      fieldName: 'window_level_remark',
      label: '窗口等级备注',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        disabled: true,
        class: 'w-full',
      },
      fieldName: 'use_shop_level',
      label: '店铺等级',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        class: 'w-full',
      },
      fieldName: 'paving_area',
      label: '铺货区域',
    },
    {
      component: 'Textarea',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        class: 'w-full',
      },
      fieldName: 'selling_point',
      label: '卖点',
    },
  ],
  wrapperClass: 'grid-cols-4',
});

interface RowType {
  is_default: boolean;
  jg_price: string;
  id: number;
  plan_id: number;
  purchase_price: string;
  supply_id: number;
}
const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    { field: 'supply_id', title: '供货商', slots: { default: 'supply_id' } },
    {
      field: 'purchase_price',
      title: '采购价',
      slots: { default: 'purchase_price' },
    },
    { field: 'jg_price', title: '加工费', slots: { default: 'jg_price' } },
    {
      field: 'is_default',
      title: '默认供应商',
      slots: { default: 'is_default' },
    },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 110,
      slots: { default: 'action' },
    },
  ],
  data: [],
  pagerConfig: {
    enabled: false,
  },
  sortConfig: {
    multiple: true,
  },
};
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

// 获取供应商列表
// 1) 远程下拉数据
const supplyOptions = ref<{ label: string; value: number }[]>([]);
const supplyLoading = ref(false);

const handleSupplySearch = useDebounceFn(async (keyword: string) => {
  supplyLoading.value = true;
  try {
    const { list } = await getFactoryIndex({
      quick_search: keyword || '',
      page: 1,
      limit: 9999,
      initKey: 'id',
      select: true,
    });
    supplyOptions.value = list.map((it: any) => ({
      label: it.SupplyNa,
      value: it.id,
    }));
  } finally {
    supplyLoading.value = false;
  }
}, 300);

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const handleSupplyDropdown = (open: boolean) => {
  if (open && supplyOptions.value.length === 0) {
    handleSupplySearch('');
  }
};

function handleIsDefaultChange(row: RowType) {
  // 如果当前行的 is_default 被设置为 true，则将其他行的 is_default 设置为 false
  if (row.is_default) {
    const tableData = gridApi.grid.getData();
    // 更新数据
    const updatedData = tableData.map((item) => {
      if (item.id !== row.id) {
        return { ...item, is_default: false }; // 其他行的 is_default 设置为 false
      }
      return item; // 当前行保持不变
    });
    gridApi.setGridOptions({ data: updatedData });
  }
}

function dleSupply(row: RowType) {
  // 获取当前表格的数据
  const tableData = gridApi.grid.getData();

  // 找到需要删除的行索引
  const rowIndex = tableData.findIndex((item) => item.id === row.id);
  // 如果找到了对应的行，则从数据中移除该行
  if (rowIndex !== -1) {
    tableData.splice(rowIndex, 1);
    // 更新表格数据
    gridApi.setGridOptions({ data: tableData });
    message.success({ content: '删除成功' });
  }
}

function addSupply() {
  // 创建一个新的行数据对象
  const newRow: any = {
    id: '', // 使用时间戳作为唯一的 ID
    supply_id: null,
    purchase_price: null,
    jg_price: null,
    is_default: false,
    plan_id: 0,
  };

  // 获取当前表格的数据
  const tableData = gridApi.grid.getData();
  // 将新行数据添加到表格数据中
  tableData.push(newRow);
  // 更新表格数据以刷新视图
  gridApi.setGridOptions({ data: tableData });
  message.success({ content: '添加成功' });
}

// 关闭弹窗
function handleFilePushData(data: any) {
  // 获取当前表单中已有的ingr_images值
  const currentValues: any = baseFormApi.getValues();
  let existingImages = currentValues.ingr_images || [];

  // 确保existingImages是数组
  if (!Array.isArray(existingImages)) {
    existingImages = [];
  }
  // 处理新数据，提取full_url组成新数组
  let newFullUrlArray = [];
  if (Array.isArray(data)) {
    newFullUrlArray = data.map((item) => item.full_url || '').filter(Boolean); // 过滤空值
  }
  // 合并新旧数据并去重
  const mergedImages = [...new Set([...existingImages, ...newFullUrlArray])];
  // 将合并后的数组设置给表单的ingr_images字段
  baseFormApi.setValues({
    ingr_images: mergedImages,
  });
  // 更新ingrImages变量，用于模板渲染
  ingrImages.value = mergedImages;
  // 显示成功提示
  message.success('文件已添加');
}
const UpdatafileList = ref([]);
const existingImages = ref([])
async function addingrImages(data: any, url: any) {
  const newUrls = url.map((item: any) => item.url);
  const mergedImages = [...existingImages.value,...newUrls]
  await baseFormApi.setValues({ ingr_images: mergedImages });
  ingrImages.value = mergedImages;
}
// 删除标签
function handleRemoveTag(index: number) {
  // 确保ingrImages是数组
  if (!Array.isArray(ingrImages.value)) {
    ingrImages.value = [];
    return;
  }
  // 创建新数组，排除要删除的项
  const newImages = ingrImages.value.filter((_, i) => i !== index);

  // 更新响应式变量
  ingrImages.value = newImages;

  // 更新表单字段
  baseFormApi.setValues({
    ingr_images: newImages,
  });

  // 显示成功提示
  message.success('文件已移除');
}
// 预览文件
function openFile(url: string) {
  window.open(url);
}

const [FileListModal, FileListModalApi] = useVbenModal({
  connectedComponent: FileList,
});

function openList() {
  FileListModalApi.setData({}).open();
}
// 货品数量标格
const hotTableComponent = ref<any>(null);
// 店均
const avgTableComponent = ref<any>(null);

const warehouseData = [
  '广州云仓',
  '南昌云仓',
  '长沙云仓',
  '贵阳云仓',
  '武汉云仓',
  '西安云仓',
];

const hotSettings = {
  contextMenu: {
    // 单元格右击展示菜单1
    items: {
      separator: Handsontable.plugins.ContextMenu.SEPARATOR,
    },
  },
  afterChange(change, source) {

    if (source == 'loadData') {
      return;
    }
    if (change) {
      change.forEach((row, i) => {
        const index = row[0];
        const field = row[1];
        const old = row[2];
        const newNum = row[3] == null ? 0 : row[3];
        const diff = newNum - old;
      });
    }
    initCurrentNum();
  },
  cells(row, col, prop) {
    const cellProperties = {};
    cellProperties.renderer = 'negativeValueRenderer';
    return cellProperties;
  },
  afterSelection(row, col, row2, col2) {
    highlight.row = row;
    highlight.col = col;

    if (avgTableComponent.value !== null) {
      avgTableComponent.value.hotInstance.loadData(showStock.avgData);
    }
  },
  fillHandle: 'vertical', // 是否开启拖拽复制操作(true,false,'horizontal'水平复制,'vertical'垂直复制)
  width: '100%',
  height: '250',
  licenseKey: '2280d-dad74-843c8-51a09-b5218',
  colHeaders: [
    '仓库',
    '上<br>柜<br>数<br>',
    '28<br>46<br>165<br>37<br>S',
    '29<br>48<br>170<br>38<br>M',
    '30<br>50<br>175<br>39<br>L',
    '31<br>52<br>180<br>40<br>XL',
    '32<br>54<br>185<br>41<br>2XL',
    '33<br>56<br>190<br>42<br>3XL',
    '34<br>58<br>195<br>43<br>4XL',
    '35<br><br><br><br>5XL',
    '36<br><br><br><br>6XL',
    '38<br><br><br><br>7XL',
    '40',
    '42<br>均码',
    '铺货备注',
    '窗口<br>等级<br>备注',
    '店铺<br>等级',
    '要求交期',
    '合计',
  ],
  copyable: true, // 允许键盘复制
  copyPaste: true, // 复制粘贴
  colWidths: 130,
  manualColumnResize: true,
  manualRowMove: true,
  columns: [
    { data: 'warehouse', width: 70 },
    { data: 'shop_num', width: 40, type: 'numeric' },
    { data: 'first', width: 40, type: 'numeric' },
    { data: 'second', width: 40, type: 'numeric' },
    { data: 'third', width: 40, type: 'numeric' },
    { data: 'fourth', width: 40, type: 'numeric' },
    { data: 'fifth', width: 40, type: 'numeric' },
    { data: 'sixth', width: 40, type: 'numeric' },
    { data: 'seventh', width: 40, type: 'numeric' },
    { data: 'eighth', width: 40, type: 'numeric' },
    { data: 'ninth', width: 40, type: 'numeric' },
    { data: 'tenth', width: 40, type: 'numeric' },
    { data: 'eleven', width: 40, type: 'numeric' },
    { data: 'twelve', width: 40, type: 'numeric' },
    { data: 'shipping_remark', width: 80 },
    { data: 'window_level_remark', width: 80 },
    { data: 'use_shop_level', width: 70 },
    {
      data: 'go_dead_line',
      width: 85,
      type: 'date',
      dateFormat: 'YYYY-MM-DD',
      correctFormat: true,
    },
    { data: 'total', width: 50, type: 'numeric' },
  ],
};

const avgSettings = {
  contextMenu: {
    // 单元格右击展示菜单
    items: {
      separator: Handsontable.plugins.ContextMenu.SEPARATOR,
    },
  },
  afterChange(change, source) {
    if (source == 'loadData') {}
  },
  cells(row, col, prop) {
    const cellProperties = {};
    cellProperties.renderer = 'negativeValueRenderer2';
    return cellProperties;
  },
  fillHandle: 'vertical', // 是否开启拖拽复制操作(true,false,'horizontal'水平复制,'vertical'垂直复制)
  width: '100%',
  height: 250,
  licenseKey: '2280d-dad74-843c8-51a09-b5218',
  colHeaders: [
    '合计',
    '上<br>柜<br>数<br>',
    '28<br>46<br>165<br>37<br>S',
    '29<br>48<br>170<br>38<br>M',
    '30<br>50<br>175<br>39<br>L',
    '31<br>52<br>180<br>40<br>XL',
    '32<br>54<br>185<br>41<br>2XL',
    '33<br>56<br>190<br>42<br>3XL',
    '34<br>58<br>195<br>43<br>4XL',
    '35<br><br><br><br>5XL',
    '36<br><br><br><br>6XL',
    '38<br><br><br><br>7XL',
    '40',
    '42<br>均码',
    '店均',
  ],
  copyable: true, // 允许键盘复制
  copyPaste: true, // 复制粘贴
  colWidths: 130,
  manualColumnResize: true,
  columns: [
    { data: 'warehouse', width: 70 },
    { data: 'shop_num', width: 40 },
    { data: 'first', width: 40 },
    { data: 'second', width: 40 },
    { data: 'third', width: 40 },
    { data: 'fourth', width: 40 },
    { data: 'fifth', width: 40 },
    { data: 'sixth', width: 40 },
    { data: 'seventh', width: 40 },
    { data: 'eighth', width: 40 },
    { data: 'ninth', width: 40 },
    { data: 'tenth', width: 40 },
    { data: 'eleven', width: 40 },
    { data: 'twelve', width: 40 },
    { data: 'total', width: 40 },
  ],
};
const fields = [
  { data: 'first' },
  { data: 'second' },
  { data: 'third' },
  { data: 'fourth' },
  { data: 'fifth' },
  { data: 'sixth' },
  { data: 'seventh' },
  { data: 'eighth' },
  { data: 'ninth' },
  { data: 'tenth' },
  { data: 'eleven' },
  { data: 'twelve' },
];

const initCurrentNum = () => {
  if (showStock.data == undefined || showStock.data.length <= 0) {
    warehouseData.forEach((row, index) => {
      showStock.data.push({
        warehouse: row,
        shop_num: 0,
        first: 0,
        second: 0,
        third: 0,
        fourth: 0,
        fifth: 0,
        sixth: 0,
        seventh: 0,
        eighth: 0,
        ninth: 0,
        tenth: 0,
        eleven: 0,
        twelve: 0,
        total: 0,
      });
    });
    showStock.data.push({
      warehouse: '合计',
      shop_num: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
    });
  }
  if (showStock.avgData == undefined || showStock.avgData.length <= 0) {
    warehouseData.forEach((row, index) => {
      showStock.avgData.push({
        warehouse: row,
        shop_num: 0,
        first: 0,
        second: 0,
        third: 0,
        fourth: 0,
        fifth: 0,
        sixth: 0,
        seventh: 0,
        eighth: 0,
        ninth: 0,
        tenth: 0,
        eleven: 0,
        twelve: 0,
        total: 0,
      });
    });
    showStock.avgData.push({
      warehouse: '全国店均',
      shop_num: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
    });
  }
  if (showStock.data == undefined) {
    return;
  }

  let total_avg_shop_num: number | string = 0;
  const total_stock = [];
  const total_avg = [];
  const total = [];

  fields.forEach((r, i) => {
    total_stock[r.data] = 0;
    total_avg[r.data] = 0;
    total[r.data] = 0;
  });
  let total_stock_num = 0;
  const max_index = 6;
  showStock.data.forEach((row, index) => {
    let index_total = 0;
    if (row.warehouse === '合计') {
      fields.forEach((r, i) => {
        index_total =
          index_total +
          Number.parseInt(
            row[r.data] == '' || row[r.data] == null ? 0 : row[r.data],
          );
      });
    } else {
      fields.forEach((r, i) => {
        index_total =
          index_total +
          Number.parseInt(
            row[r.data] == '' || row[r.data] == null ? 0 : row[r.data],
          );
        total[r.data] =
          total[r.data] +
          Number.parseInt(
            row[r.data] == '' || row[r.data] == null ? 0 : row[r.data],
          );
      });
      fields.forEach((r, i) => {
        showStock.data[max_index][r.data] = total[r.data];
      });
    }
    showStock.data[index].total = index_total;
    const shop_num = Math.max(showStock.data[index].shop_num, 0);
    if (index < max_index) {
      showStock.avgData[index].shop_num = shop_num;
      showStock.data[index].shop_num = shop_num;
      fields.forEach((r, i) => {
        showStock.avgData[index][r.data] =
          shop_num <= 0
            ? 0
            : (showStock.data[index][r.data] / shop_num).toFixed(1);
        total_stock[r.data] =
          total_stock[r.data] + showStock.data[index][r.data];
        showStock.data[max_index][r.data] = total_stock[r.data];
        total_stock_num = total_stock_num + showStock.data[index][r.data];
      });
      showStock.avgData[index].total =
        shop_num <= 0 ? 0 : (showStock.data[index].total / shop_num).toFixed(1);
      showStock.data[max_index].total = total_stock_num;
      total_avg_shop_num = total_avg_shop_num + Number.parseInt(shop_num);
    } else {
      fields.forEach((r, i) => {
        total_avg[r.data] =
          total_avg_shop_num <= 0
            ? 0
            : (showStock.data[max_index][r.data] / total_avg_shop_num).toFixed(
                1,
              );
        showStock.avgData[max_index][r.data] = total_avg[r.data];
      });
      showStock.avgData[max_index].shop_num = total_avg_shop_num;
      showStock.data[max_index].shop_num = total_avg_shop_num;
      const avgData_total = showStock.data[max_index].total;
      showStock.avgData[max_index].total =
        total_avg_shop_num > 0
          ? (avgData_total / showStock.data[max_index].shop_num).toFixed(1)
          : 0;
    }
  });
};
const showStock = reactive({
  showData: false,
  totalData: ref([]),
  data: ref([]),
  avgData: ref([]),
  stockData: ref([]),
  currentIndex: ref(0),
  total: 0,
  currentPage: 1,
  quickSearch: '',
  goods_no: '',
  category_name: '',
  style_category_name: '',
  time_category_name: '',
  shipping_remark: '',
  retailData: ref([]),
  warehouseTotalData: ref([]),
});
watch(
  () => showStock.data,
  (newValue, oldValue) => {
    if (showStock.data !== undefined) {
      initCurrentNum();
    }
  },
);

// 添加提交审批弹窗
const [submitApprovalModal, submitApprovalModalApi] = useVbenModal({
  connectedComponent: submitApproval,
});
// 提交审批回来
function submitAppr(data: any) {
  baseFormApi.setValues({ is_confirm_price_update: true }, false);
  baseFormApi.setValues({ create_approval_text: data }, false);
  save();
}
</script>

<template>
  <Modal
    :title="
      currentView === 'edit' ? '编辑' : currentView === 'add' ? '新建' : '拷贝'
    "
  >
    <Page content-class="flex flex-col gap-4" description="" title="">
      <BaseForm>
        <template #_divider>
          <Divider orientation="left">基础信息</Divider>
        </template>
        <template #goods_images>
          <Row style="height: 200px; width: 100%; overflow-y: auto">
            <Col span="24">
              <ImageUploader
                v-model:value="goodsImages"
                :multiple="true"
                accept=".jpg,.jpeg,.png,.gif"
                :max-count="9"
                upload-text="上传货品图片"
              />
            </Col>
          </Row>
        </template>
        <template #ingr_images>
          <Row style="height: 200px; width: 100%">
            <Col span="24">
              <div>
                <Space>
                  <adapterFileLists
                    v-model:file-list="UpdatafileList"
                    :multiple="true"
                    @upload-success="
                      (url) => addingrImages(UpdatafileList, url)
                    "
                  />
                  <Button type="primary" @click="openList()">选择</Button>
                </Space>
              </div>
              <template v-if="ingrImages && ingrImages.length > 0">
                <div
                  style="max-height: 200px; overflow-y: auto; padding: 8px 0"
                >
                  <div
                    v-for="(url, index) in ingrImages"
                    :key="index"
                    style="margin-bottom: 4px"
                  >
                    <Tag
                      @click="openFile(url)"
                      closable
                      @close="handleRemoveTag(index)"
                    >
                      {{ url.split('/').pop() }}
                    </Tag>
                  </div>
                </div>
              </template>
            </Col>
          </Row>
        </template>
        <template #purchInfo>
          <Divider orientation="left">本次采购信息</Divider>
        </template>
        <template #warehouse>
          <Divider orientation="left">
            分仓信息，总数量：{{ p__plan_total_num }}
          </Divider>
        </template>
        <template #compartment>
          <Row style="width: 100%">
            <Col span="14">
              <HotTable
                style="width: 110%"
                ref="hotTableComponent"
                :data="showStock.data"
                :settings="hotSettings"
              />
            </Col>
            <Col span="10">
              <HotTable
                style="width: 100%"
                ref="avgTableComponent"
                :data="showStock.avgData"
                :settings="avgSettings"
              />
            </Col>
          </Row>
        </template>
        <template #Store> </template>
        <template #_divider1>
          <Divider orientation="left">基础信息</Divider>
        </template>
        <template #_divider2>
          <Divider orientation="left">分类信息</Divider>
        </template>
        <template #_divider3>
          <Divider orientation="left">
            价格信息
            <span style="color: red" v-if="is_price_checking">【有价格正在审核中,审核期间资料价格和供应商价格不允许再次修改！！！！！】</span>
          </Divider>
        </template>
        <template #_divider4>
          <Divider orientation="left">供应商当前价格信息</Divider>
        </template>
        <template #but>
          <div style="width: 100%">
            <div style="width: 100%; display: flex; justify-content: flex-end">
              <Button type="primary" size="small" @click="addSupply()">
                添加
              </Button>
            </div>
            <Grid>
              <template #supply_id="{ row }">
                <Select
                  v-model:value="row.supply_id"
                  show-search
                  allow-clear
                  placeholder="请输入供应商关键词"
                  :filter-option="false"
                  :options="supplyOptions"
                  :loading="supplyLoading"
                  @search="handleSupplySearch"
                  @dropdown-visible-change="handleSupplyDropdown"
                  style="width: 100%"
                />
              </template>
              <template #purchase_price="{ row }">
                <InputNumber
                  min="0"
                  step="1"
                  :disabled="is_price_checking"
                  style="width: 100%"
                  placeholder="请输入采购价"
                  v-model:value="row.purchase_price"
                />
              </template>
              <template #jg_price="{ row }">
                <InputNumber
                  min="0"
                  step="1"
                  style="width: 100%"
                  placeholder="请输入加工费"
                  v-model:value="row.jg_price"
                />
              </template>
              <template #is_default="{ row }">
                <Switch
                  v-model:checked="row.is_default"
                  @change="() => handleIsDefaultChange(row)"
                />
              </template>
              <template #action="{ row }">
                <Button
                  type="primary"
                  danger
                  size="small"
                  @click="dleSupply(row)"
                >
                  删除
                </Button>
              </template>
            </Grid>
          </div>
        </template>
        <template #_divider5>
          <Divider orientation="left">属性信息</Divider>
        </template>
      </BaseForm>
      <FileListModal @push-data="handleFilePushData" />
      <submitApprovalModal @push-data="submitAppr" />
    </Page>
  </Modal>
</template>

<style scoped>
/* 让 Form.Item 不再有默认 margin-bottom */
.mb-0 {
  margin-bottom: 0 !important;
}
</style>
